package com.example.nettyserver.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.HttpRetryException;
import java.nio.ByteBuffer;

public class SomeServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * channel中有来自于客户端的数据时就会触发该方法的执行
     * @param ctx 上下文对象
     * @param msg  来自于客户端的数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("msg = " + msg.getClass());
        if (msg instanceof HttpRequest){
            HttpRequest req = (HttpRequest) msg;
            System.out.println("请求方式：" + req.method().name());
            System.out.println("请求urI：" + req.uri());
            if ("favicon.ico".equals(req.uri())){
                return;
            }
            ByteBuf body = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, body);
            HttpHeaders headers = response.headers();
            headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            headers.set(HttpHeaderNames.CONTENT_LENGTH, body.readableBytes());
            System.out.println("请求链接");
            ctx.writeAndFlush(response)
                    //添加监听器，响应体发送完毕则直接将channel关闭
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
